<template>
  <view class="shop-detail">
    <view v-if="shop" class="shop-info">
      <view class="shop-name">{{ shop.name }}</view>
      <view class="address">地址：{{ shop.address }}</view>
      <view class="distance">距离：{{ shop.distance }} 米</view>
      <view class="shop-price">价格：¥{{ shop.price }} / 分钟</view>
    </view>
    <view v-else class="loading">
      <text>加载中...</text>
    </view>

    <!-- 新增：桌台信息展示 -->
    <view class="tables-section">
      <view class="table-status">
        <text>空闲 {{ shop.tables }}</text>
        <text>中式台球</text>
      </view>

      <view class="table-title">
        <text>桌台</text>
      </view>

      <view class="tables-list">
        <view v-for="(table, index) in shop.tablesList"
              :key="index"
              class="table-item"
              :class="{ occupied: isTableOccupied(table.number) }">
          <text class="table-number">{{ table.number }}</text>
          <view class="table-buttons">
            <button class="reserve-button" @click="navigateToReserve(table.number)">预定</button>
            <button class="start-button"
                    :disabled="isTableOccupied(table.number)"
                    @click="navigateToStart(table.number)">
              立即开台
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 扫码开台按钮 -->
    <view class="scan-to-start">
      <button class="scan-button"  @click="handleScanCode">扫码开台</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shopId: null,
      shop: null,
      occupiedTables: [], // 存储被占用的桌号
      mockShops: [
        {
          id: 1,
          name: '中山电子科技大学店',
          price: 0.46,
          tables: 5,
          address: '广东省中山市石岐区街道龙凤街4号溢彩荟2期4楼403小铁24h无人自助台...',
          distance: 319,
          closest: true,
          tablesList: [ // 模拟桌台信息
            { number: 'A01' },
            { number: 'A02' },
            { number: 'A03' },
            { number: 'A04' }
              ]
        },
        {
          id: 2,
          name: '中山石岐新都会店',
          price: 0.46,
          tables: 6,
          address: '广东省中山市中山市大信中路石岐大信新都汇A座2层',
          distance: 790,
          closest: false,
          tablesList: [ // 模拟桌台信息
            { number: 'A01' },
            { number: 'A02' },
            { number: 'A03' },
            { number: 'A04' }
              ]
        }
      ]
    };
  },
  computed: {
    occupiedOrReservedTables() {
      const now = new Date().getTime();
      const ordersList = uni.getStorageSync('ordersList') || [];

      return ordersList
          .filter(order => order.status === 'pendingUse')
          .map(order => {
            const scheduledStartTime = order.scheduledStartTime;
            const tenMinutesLater = scheduledStartTime + 10 * 60 * 1000; // 10分钟后的时间戳

            return {
              tableNumber: order.tableNumber,
              isWithinTime: now >= scheduledStartTime && now <= tenMinutesLater
            };
          });
    }
  },
  onLoad(options) {
    if (options.id) {
      this.shopId = options.id;
      this.fetchShopDetail(options.id);
    }
    this.loadOccupiedTables(); // 加载已占用桌号

    // 清除过期的缓存数据
    const now = new Date().getTime();
    const ordersList = uni.getStorageSync('ordersList') || [];
    const filteredOrders = ordersList.filter(order => order.status !== 'processing' || now - order.startTime < 4 * 60 * 60 * 1000); // 保留未超时的订单
    uni.setStorageSync('ordersList', filteredOrders);

    // 监听
    uni.$on('updateOccupiedTables', () => {
      console.log('收到 updateOccupiedTables 事件');
      this.loadOccupiedTables(); // 更新占用列表
      this.$forceUpdate(); // 强制更新模板以重新计算 computed
    });
  },
  onShow() {
    this.loadOccupiedTables(); // 每次页面展示都重新加载，保证最新状态
  },
  onUnload() {
    // 页面卸载时移除监听
    uni.$off('updateOccupiedTables', this.loadOccupiedTables);
  },
  methods: {

    isTableOccupied(number) {
      const match = this.occupiedOrReservedTables.find(
          item => item.tableNumber === number
      );
      if (match && match.isWithinTime) return true;

      // 查看是否在 occupiedTables 中（立即开台导致的占用）
      if (this.occupiedTables.includes(number)) return true;

      return false;
    },
    loadOccupiedTables() {
      this.occupiedTables = uni.getStorageSync('occupiedTables') || [];
    },
    fetchShopDetail(id) {
      // 模拟从本地数据查找店铺信息
      const foundShop = this.mockShops.find(shop => shop.id == id);
      this.shop = foundShop || null;

      // 实际开发中你可以用接口请求：
      // uni.request({
      //   url: `https://api.example.com/shops/${id}`,
      //   success: (res) => {
      //     this.shop = res.data;
      //   }
      // });
    },
    navigateToReserve(tableNumber) {
      uni.navigateTo({
        url: `/pages/tabbar/tabbar-2-detail/reserve?tableNumber=${tableNumber}&shopName=${this.shop.name}&price=${parseFloat(this.shop.price)}`
      });
    },
    navigateToStart(tableNumber) {
      uni.navigateTo({
        url: `/pages/tabbar/tabbar-2-detail/start?tableNumber=${tableNumber}&shopName=${this.shop.name}&type=中式台球&price=${this.shop.price}&startTime=${new Date().getTime()}`
      });
    },
  }
};

</script>

<style scoped>.shop-detail {
  padding: 20rpx;
  background-color: #fff;
}

.shop-info {
  border-bottom: 1rpx solid #eee;
  padding: 20rpx;
}

.shop-name{
  font-size: 42rpx;
  font-weight: bold;
  margin-bottom: 15rpx;
}

.address{
  display: block;
  width: 400rpx; /* 根据字体大小调整，大致容纳10个汉字 */
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 26rpx;
  color: #666;
}

.distance{
  font-size: 26rpx;
  color: #666;
  font-weight: bold;
}

.shop-price{
  font-size: 26rpx;
  color: #666;
  font-weight: bold;
}

/* 新增：桌台信息样式 */
.tables-section {
  margin-top: 20rpx;
  padding: 20rpx;
}

.table-status {
  display: flex;
  flex-direction: column; /* 改为纵向排列 */
  align-items: center;    /* 居中对齐 */
  margin-bottom: 20rpx;
}

.table-status text:first-child {
  color: #666;
  font-size: 28rpx;       /* 空闲数量字体大小 */
  margin-bottom: 6rpx;   /* 和下面文字间隔 */
}

.table-status text:nth-child(2) {
  font-size: 36rpx;        /* 中式台球字体加大 */
  font-weight: bold;       /* 加粗显示 */
  color: #333;
}

.table-title{
  margin-bottom: 30rpx;
  font-weight: bold;
  font-size: 36rpx;
}

.tables-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.table-item {
  width: 48%; /* 每行两个桌台 */
  background-color: #4caf50;
  border-radius: 10rpx;
  padding: 50rpx;
  margin-bottom: 20rpx;
  box-sizing: border-box;
  position: relative;
  border: 20rpx solid #388e3c; /* 深绿色边框 */
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1); /* 轻微阴影增加立体感 */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.table-number {
  font-size: 40rpx;
  color: #fff;
  text-align: center;
  margin-bottom: 10rpx;
}

.table-buttons {
  display: flex;
  justify-content: space-between;
}

.table-item.occupied {
  background-color: #e53935; /* 红色背景表示已占用 */
  color: white;
}

.table-item.occupied .reserve-button,
.table-item.occupied .start-button {
  background-color: rgba(255, 255, 255, 0.3); /* 按钮变灰 */
  color: white;
  opacity: 0.7;
}

.reserve-button{
  flex: 3;
  height: 55rpx;
  line-height: 60rpx;
  text-align: center;
  border-radius: 25rpx;
  color: #fff;
  background-color: rgba(0, 255, 21, 0.58);
  margin: 10rpx;
  padding: 0 10rpx; /* 增加左右内边距 */
  white-space: nowrap; /* 禁止换行，保持一行显示 */
  font-size: 26rpx;
}

.start-button {
  flex: 5;
  height: 55rpx;
  line-height: 60rpx;
  text-align: center;
  border-radius: 25rpx;
  color: #fff;
  background-color: rgba(0, 255, 21, 0.58);
  margin: 10rpx;
  padding: 0 10rpx; /* 增加左右内边距 */
  white-space: nowrap; /* 禁止换行，保持一行显示 */
  font-size: 26rpx;
}

.scan-to-start {
  margin-top: 40rpx;
  text-align: center;
}

.scan-button {
  width: 80%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #ffc107;
  color: #fff;
  border-radius: 40rpx;
  font-size: 32rpx;
}
</style>